package com.ruoyi.maode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.ButtonEums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.maode.domain.dto.ApproveRequestDTO;
import com.ruoyi.maode.domain.dto.QueryFlowableDTO;
import com.ruoyi.maode.domain.entity.Part;
import com.ruoyi.maode.domain.entity.PartBatch;
import com.ruoyi.maode.domain.entity.PartReport;
import com.ruoyi.maode.domain.entity.Supplier;
import com.ruoyi.maode.domain.vo.*;
import com.ruoyi.maode.mapper.FlowableMapper;
import com.ruoyi.maode.service.*;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysUserRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.util.PageQuery;
import com.ruoyi.web.util.QyWx.SendQyWxMsgUtils;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 审批流程接口实现类
 * @author zhangwenqiang
 */
@Service
@Slf4j
public class ApproveRequestProcessServiceImpl implements ApproveRequestProcessService {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private PartReportService partReportService;

    @Autowired
    private PartBatchService partBatchService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private PartService partService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private FlowableMapper flowableMapper;

    @Value("${flowable.xml-path}")
    private String xmlPath;

    @Value("${server.url}")
    private String serverUrl;

    @Value("${qywx.url}")
    private String qywxUrl;

    @Override
    public void approveRequest(ApproveRequestDTO approveRequestDTO) {

        Part part = partService.getOne(new LambdaQueryWrapper<Part>().eq(Part::getPartCode, approveRequestDTO.getPartCode()).eq(Part::getIsDelete,Constants.CONSTANTS_ZERO));
        // 获取批次生成的报告
        PartReport partReport = partReportService.getOne(new LambdaQueryWrapper<PartReport>()
                .eq(PartReport::getBatchId, approveRequestDTO.getBatchId())
                .eq(PartReport::getPartId,part.getId()));

        // 组装参数
        Map<String, Object> variables = new HashMap<>(8);
        variables.put("approve", approveRequestDTO.getApprove());
        variables.put("partReportUrl", serverUrl  + partReport.getReportUrl());
        variables.put("assignee", 2);
        variables.put("approveUserName", "廖勇");
        variables.put("submitUserId", SecurityUtils.getUserId());
        SysUser SysUser = userService.selectUserById(SecurityUtils.getUserId());
        variables.put("submitUserName", SysUser.getNickName());
        variables.put("status", "未审批");
        variables.put("createTime", DateUtils.getTime());
        variables.put("approveTime", DateUtils.getTime());
        variables.put("partCode", approveRequestDTO.getPartCode());
        // 获取批次Code
        PartBatch partBatch = partBatchService.getOne(new LambdaQueryWrapper<PartBatch>().eq(PartBatch::getId, approveRequestDTO.getBatchId()));
        variables.put("partBatchCode", partBatch.getBatchCode());
        // 启动流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(Constants.PROCESS_KEY, variables);
        runtimeService.updateBusinessStatus(processInstance.getId(), "未审批");

    }


    @Override
    public Page<FlowableVO> getTask(PageQuery<QueryFlowableDTO> param) {
        QueryFlowableDTO dto = param.getData();

        List<Task> tasks = new ArrayList<>();
        // 超级管理员获取所有数据
        Long roleId = sysUserRoleService.getRole(SecurityUtils.getUserId());
        // 判断当前用户是否为超级管理员、总经理、总经理助理
        if (roleId == 1 || roleId == 105 || roleId == 108) {
            tasks = taskService.createTaskQuery().list();
        } else {
            // 查询当前登录人ID
            tasks = taskService.createTaskQuery().taskAssignee(String.valueOf(SecurityUtils.getUserId())).list();
        }

        // 打印查询到的任务信息
        System.out.println("你有 " + tasks.size() + " 任务:");
        for (int i = 0; i < tasks.size(); i++) {
            System.out.println((i + 1) + ") " + tasks.get(i).getName() + "任务ID：" +tasks.get(i).getId());
        }

        // 获取要执行的所有任务
        List<FlowableVO> flowableVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(tasks)) {
            for (Task task : tasks) {
                FlowableVO vo = new FlowableVO();
                Map<String, Object> processVariables = taskService.getVariables(task.getId());
                vo.setTaskId(task.getId());
                vo.setProcessInstanceId(task.getProcessInstanceId());
                vo.setTaskName(task.getName());
                vo.setPartBatchCode(String.valueOf(processVariables.get("partBatchCode")));
                vo.setApprove(String.valueOf(processVariables.get("approve")));
                vo.setApproveTime(String.valueOf(processVariables.get("approveTime")));
                vo.setApproveUserName(String.valueOf(processVariables.get("approveUserName")));
                vo.setSubmitUserId(Long.valueOf(String.valueOf(processVariables.get("submitUserId"))));
                vo.setCreateTime(String.valueOf(processVariables.get("createTime")));
                vo.setApproveStatus(String.valueOf(processVariables.get("status")));
                vo.setApproveUserId(Long.valueOf(String.valueOf(processVariables.get("assignee"))));
                vo.setSubmitUserName(String.valueOf(processVariables.get("submitUserName")));
                vo.setReportUrl(String.valueOf(processVariables.get("partReportUrl")));
                // 获取供应商
                Part part = partService.getOne(new LambdaQueryWrapper<Part>()
                        .eq(Part::getPartCode, String.valueOf(processVariables.get("partCode")))
                        .eq(Part::getIsDelete,Constants.CONSTANTS_ZERO));
                PartBatch partBatch = partBatchService.getOne(new LambdaQueryWrapper<PartBatch>()
                        .eq(PartBatch::getBatchCode, String.valueOf(processVariables.get("partBatchCode")))
                        .eq(PartBatch::getPartId, part.getId()));
                // 获取供应商
                Supplier supplier = supplierService.getOne(new LambdaQueryWrapper<Supplier>().eq(Supplier::getId, partBatch.getSupplierId()));
                // 获取毛坯供应商
                if (partBatch.getRoughSupplierId() != null) {
                    Supplier roughSupplier = supplierService.getOne(new LambdaQueryWrapper<Supplier>().eq(Supplier::getId, partBatch.getRoughSupplierId()));
                    vo.setRoughSupplierName(roughSupplier.getSupplierName());
                }
                vo.setPartCode(part.getPartCode());
                vo.setSupplierName(supplier.getSupplierName());

                if (SecurityUtils.getUserId() == 1 || SecurityUtils.getUserId() == 105 || SecurityUtils.getUserId() == 113) {
                    vo.setIsAdmin(1);
                } else {
                    vo.setIsAdmin(0);
                }
                flowableVOS.add(vo);

                // 过滤批次编码
                if (!dto.getPartBatchCode().isEmpty()) {
                    flowableVOS = flowableVOS.stream()
                            .filter(flowableVO -> dto.getPartBatchCode().equals(flowableVO.getPartBatchCode()))
                            .collect(Collectors.toList());
                }
                // 过滤时间
                if (dto.getCreateTime() != null) {
                    String date = DateUtils.dateTime(dto.getCreateTime());
                    flowableVOS = flowableVOS.stream()
                            .filter(flowableVO -> date.equals(DateUtils.getYyyyMmDd(flowableVO.getCreateTime())))
                            .collect(Collectors.toList());
                }
                // 同时过滤时间和批次编码
                if (dto.getCreateTime() != null && !dto.getPartBatchCode().isEmpty()) {
                    String date = DateUtils.dateTime(dto.getCreateTime());
                    flowableVOS = flowableVOS.stream()
                            .filter(flowableVO -> dto.getPartBatchCode().equals(flowableVO.getPartBatchCode()))
                            .filter(flowableVO -> date.equals(DateUtils.getYyyyMmDd(flowableVO.getCreateTime())))
                            .collect(Collectors.toList());
                }
            }
        }
        Page<FlowableVO> flowableVOPage = convertListToPage(flowableVOS, param.getPage(), param.getPageSize(), tasks.size());
        return flowableVOPage;
    }

    @Override
    public FlowableVO getTaskDetail(String taskId) {
        // 获取当前task中候选用户
        List<String> candidateUsers = getCandidateUsers(taskId);
        List<CandidateUsersVO> candidateUsersVOS = new ArrayList<>();
        // 使用 stream 流遍历每个 userId，并进行数据库查询
        candidateUsers.stream()
                .forEach(userId -> {
                    // 使用 userId 构造查询条件
                    LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SysUser::getUserId, userId);

                    // 使用 userId 执行查询操作
                    SysUser sysUser = userService.selectUserById(Long.valueOf(userId));

                    // 如果查询到用户，则包装到 CandidateUsersVO 中
                    if (sysUser != null) {
                        CandidateUsersVO candidateUsersVO = new CandidateUsersVO();
                        candidateUsersVO.setUserId(String.valueOf(sysUser.getUserId()));
                        candidateUsersVO.setUserName(sysUser.getNickName());
                        candidateUsersVOS.add(candidateUsersVO);
                    }
                });

        FlowableVO vo = new FlowableVO();
        Map<String, Object> processVariables = taskService.getVariables(taskId);
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        vo.setTaskId(task.getId());
        vo.setProcessInstanceId(task.getProcessInstanceId());
        vo.setTaskName(task.getName());
        vo.setCandidateUsers(candidateUsersVOS);
        vo.setApprove(String.valueOf(processVariables.get("approve")));
        vo.setApproveTime(String.valueOf(processVariables.get("approveTime")));
        vo.setApproveUserName(String.valueOf(processVariables.get("approveUserName")));
        vo.setSubmitUserId(Long.valueOf(String.valueOf(processVariables.get("submitUserId"))));
        vo.setCreateTime(String.valueOf(processVariables.get("createTime")));
        vo.setApproveStatus(String.valueOf(processVariables.get("status")));
        vo.setApproveUserId(Long.valueOf(String.valueOf(processVariables.get("assignee"))));
        vo.setSubmitUserName(String.valueOf(processVariables.get("submitUserName")));
        vo.setReportUrl(String.valueOf(processVariables.get("partReportUrl")));
        vo.setPartBatchCode(String.valueOf(processVariables.get("partBatchCode")));
        vo.setApprove(String.valueOf(processVariables.get("approve")));
        vo.setPartCode(String.valueOf(processVariables.get("partCode")));
        return vo;
    }

    @Override
    public Page<FlowableVO> getCompletedTask(PageQuery<QueryFlowableDTO> param) {
        QueryFlowableDTO dto = param.getData();
        List<HistoricProcessInstance> instances = historyService.createHistoricProcessInstanceQuery()
                .orderByProcessInstanceStartTime().desc()  // 按开始时间降序排序
                .list();
        // 获取执行完的所有任务
        List<FlowableVO> flowableVOS = new ArrayList<>();
        for (HistoricProcessInstance instance : instances) {
            FlowableVO vo = new FlowableVO();
            vo.setTaskId(instance.getId());
            vo.setProcessInstanceId(instance.getId());
            vo.setCreateTime(DateUtils.getYyyyMmDdHhMmSs(instance.getStartTime()));
            SysUser user = userService.selectUserByUserName(instance.getStartUserId());
            vo.setSubmitUserName(user.getNickName());
            if (instance.getEndTime() != null) {
                vo.setApproveTime(DateUtils.getYyyyMmDdHhMmSs(instance.getEndTime()));
            }
            vo.setApproveStatus(instance.getBusinessStatus());
            if(instance.getBusinessStatus().equals("审批完成")){
                vo.setPartBatchCode(getVariables(instance,"partBatchCode"));
                vo.setPartCode(getVariables(instance,"partCode"));
                vo.setReportUrl(getVariables(instance,"partReportUrl"));
                vo.setResult(getVariables(instance,"result"));
                vo.setApprove(getVariables(instance,"approve"));
                vo.setApproveTime(DateUtils.getYyyyMmDdHhMmSs(instance.getEndTime()));
                flowableVOS.add(vo);
            }
            // 过滤批次编码
            if (!dto.getPartBatchCode().isEmpty()) {
                flowableVOS = flowableVOS.stream()
                        .filter(flowableVO -> dto.getPartBatchCode().equals(flowableVO.getPartBatchCode()))
                        .collect(Collectors.toList());
            }
            // 过滤时间
            if (dto.getCreateTime() != null) {
                String date = DateUtils.dateTime(dto.getCreateTime());
                flowableVOS = flowableVOS.stream()
                        .filter(flowableVO -> date.equals(DateUtils.getYyyyMmDd(flowableVO.getCreateTime())))
                        .collect(Collectors.toList());
            }
            // 同时过滤时间和批次编码
            if (dto.getCreateTime() != null && !dto.getPartBatchCode().isEmpty()) {
                String date = DateUtils.dateTime(dto.getCreateTime());
                flowableVOS = flowableVOS.stream()
                        .filter(flowableVO -> dto.getPartBatchCode().equals(flowableVO.getPartBatchCode()))
                        .filter(flowableVO -> date.equals(DateUtils.getYyyyMmDd(flowableVO.getCreateTime())))
                        .collect(Collectors.toList());
            }
        }
        Page<FlowableVO> flowableVOPage = convertListToPage(flowableVOS, param.getPage(), param.getPageSize(), flowableVOS.size());

        return flowableVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(ApproveRequestDTO dto) {
        // 组装参数
        Map<String, Object> variables = new HashMap<>(2);

        // 获取审批的零件
        Part part = partService.getOne(new LambdaQueryWrapper<Part>().eq(Part::getPartCode, dto.getPartCode())
                .eq(Part::getIsDelete,Constants.CONSTANTS_ZERO));

        // 指定待审批人
        if (dto.getAssignee() != null) {
            variables.put("assignee", dto.getAssignee());
            SysUser sysUser = userService.selectUserById(dto.getAssignee());
            variables.put("approveUserName", sysUser.getNickName());
        }
        variables.put("result", dto.getApproveState());
        if (dto.getApprove() != null) {
            variables.put("approve", dto.getApprove());
        }
        variables.put("status", "审批中");
        variables.put("approveTime", DateUtils.getTime());
        variables.put("partCode", dto.getPartCode());

        // 执行完成
        taskService.complete(dto.getTaskId(), variables);
        // 如果是检验员复检直接删除之前的流程实例
        Long role = sysUserRoleService.getRole(SecurityUtils.getUserId());
        if ("106".equals(String.valueOf(role))) {
            List<String> taskIds = flowableMapper.selectTaskId(dto.getProcessInstanceId());
            if (taskIds.size() > 1) {
            flowableMapper.deleteHisToryTaskId(taskIds.get(0));
            flowableMapper.deleteTaskId(taskIds.get(0));
            flowableMapper.deleteHistoryDetail();
            }
        }
        // 技术部长审核完成为让步使用
        if ("104".equals(String.valueOf(role)) && dto.getApproveState().equals(Constants.CONSTANTS_ONE)) {
            flowableMapper.updateStatus(dto.getProcessInstanceId(), new Date(), Constants.OK_PROCESS_ID);
            partBatchService.update(new LambdaUpdateWrapper<PartBatch>()
                    .set(PartBatch::getResult, Constants.CONSTANTS_ONE)
                    .set(PartBatch::getUpdateTime, new Date())
                    .eq(PartBatch::getBatchCode, dto.getPartBatchCode())
                    .eq(PartBatch::getPartId, part.getId()));
            flowableMapper.updateBusinessStatus(dto.getProcessInstanceId(),"审批完成");
            // 转发配套部、物资部
            try {
                SendQyWxMsgUtils.sendFinishText(dto.getReportUrl() + "", dto.getPartBatchCode(), part.getPartCode(), part.getPartDescription(),qywxUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            // 查看审批任务是否结束
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(dto.getProcessInstanceId())
                    .singleResult();
            if (processInstance == null) {
                // 如果当前总经理审批--只有降价同意是总经理审批
                if(SecurityUtils.getUserId() == 105){
                    // 转发配套部、物资部、财务部入库
                    try {
                        SendQyWxMsgUtils.sendPriceReductionText(dto.getReportUrl() + "",dto.getPartBatchCode(),dto.getPartCode(),part.getPartDescription(),qywxUrl);
                        // 更新该批次结果
                        partBatchService.update(new LambdaUpdateWrapper<PartBatch>()
                                .set(PartBatch::getResult, Constants.CONSTANTS_ONE)
                                .set(PartBatch::getUpdateTime,new Date())
                                .eq(PartBatch::getBatchCode, dto.getPartBatchCode())
                                .eq(PartBatch::getPartId,part.getId()));
                        flowableMapper.updateBusinessStatus(dto.getProcessInstanceId(),"审批完成");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    log.info("已告知财务此批次降价处理");
                } else {
                    HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery()
                            .processInstanceId(dto.getProcessInstanceId())
                            .singleResult();
                    // 结束流程为合格--入库
                    if (Constants.OK_PROCESS_ID.equals(instance.getEndActivityId())) {
                        // 更新该批次结果
                        partBatchService.update(new LambdaUpdateWrapper<PartBatch>()
                                .set(PartBatch::getResult,Constants.CONSTANTS_ONE)
                                .set(PartBatch::getUpdateTime,new Date())
                                .eq(PartBatch::getBatchCode, dto.getPartBatchCode())
                                .eq(PartBatch::getPartId, part.getId()));
                        flowableMapper.updateBusinessStatus(dto.getProcessInstanceId(),"审批完成");
                        // 转发配套部、物资部入库
                        try {
                            SendQyWxMsgUtils.sendFinishText(dto.getReportUrl() + "", dto.getPartBatchCode(), part.getPartCode(),part.getPartDescription(), qywxUrl);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        log.info("已发送推送通知告知配套部批次"+dto.getPartBatchCode()+"审核完成，办理入库！");

                    } else { // 结束流程为不合格--退货
                        // 更新该批次结果
                        partBatchService.update(new LambdaUpdateWrapper<PartBatch>()
                                .set(PartBatch::getResult,Constants.CONSTANTS_ZERO)
                                .set(PartBatch::getUpdateTime,new Date())
                                .eq(PartBatch::getBatchCode, dto.getPartBatchCode())
                                .eq(PartBatch::getPartId, part.getId()));
                        flowableMapper.updateBusinessStatus(dto.getProcessInstanceId(),"审批完成");
                        // 转发配套部、物资部入库
                        try {
                            SendQyWxMsgUtils.sendReturnText(dto.getReportUrl() + "", dto.getPartBatchCode(), part.getPartCode(),part.getPartDescription(), qywxUrl);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        log.info("已发送推送通知告知配套部批次"+dto.getPartBatchCode()+"审核完成，办理退货！");
                    }
                }
            }
        }
    }

    @Override
    public List<ApproveNodeVO> getHistory(String processInstanceId) {
        // 历史数据
        List<HistoricActivityInstance> activities =
                historyService.createHistoricActivityInstanceQuery()
                        .processInstanceId(processInstanceId)
                        .orderByHistoricActivityInstanceStartTime().asc()
                        .list();
        List<ApproveNodeVO> flowableVOS = new ArrayList<>();
        for (HistoricActivityInstance activity : activities) {
            ApproveNodeVO nodeVO = new ApproveNodeVO();
            nodeVO.setProcessInstanceId(activity.getProcessInstanceId());
            if ("userTask".equals(activity.getActivityType())) {
                // 获取该任务的审核操作
                ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
                HistoricTaskInstance historicTask = processEngine.getHistoryService()
                        .createHistoricTaskInstanceQuery()
                        .taskId(activity.getTaskId())  // 使用活动实例中的任务 ID
                        .singleResult();
                nodeVO.setApproveResult(historicTask.getDescription());
                nodeVO.setApprove(String.valueOf(historicTask.getProcessVariables().get("approve")));


                SysUser sysUser = new SysUser();
                if (activity.getAssignee() != null) {
                    sysUser = userService.selectUserById(Long.valueOf(activity.getAssignee()));
                }
                nodeVO.setApproveUserName(sysUser.getNickName());
                nodeVO.setNodeName(activity.getActivityName());
                if (activity.getEndTime() != null) {
                    nodeVO.setApproveTime(DateUtils.getYyyyMmDdHhMmSs(activity.getEndTime()));
                    nodeVO.setApproveStatus(Constants.CONSTANTS_ONE);
                    flowableVOS.add(nodeVO);
                } else {
                    nodeVO.setApproveStatus(Constants.CONSTANTS_ZERO);
                    flowableVOS.add(nodeVO);
                }

            }

        }
        return flowableVOS;
    }

//    @Override
//    public List<ButtonVO> getApproveSubmit() {
//        Long role = sysUserRoleService.getRole(SecurityUtils.getUserId());
//        List<ButtonVO> buttonVOS = new ArrayList<>();
//        List<ButtonVO> button = sysButtonRoleUserService.getButton();
//
//        switch (role.intValue()) {
//            // 品质部长
//            case 100:
//                buttonVOS.add(new ButtonVO(ButtonEums.RBSY_BUTTON.getValue(), ButtonEums.RBSY_BUTTON.getDescription()));
//                buttonVOS.add(new ButtonVO(ButtonEums.OK_BUTTON.getValue(), ButtonEums.OK_BUTTON.getDescription()));
//                buttonVOS.add(new ButtonVO(ButtonEums.TXSY_BUTTON.getValue(), ButtonEums.TXSY_BUTTON.getDescription()));
//                buttonVOS.add(new ButtonVO(ButtonEums.JJCL_BUTTON.getValue(), ButtonEums.JJCL_BUTTON.getDescription()));
//                break;
//            case 101:
//                buttonVOS.add(new ButtonVO(ButtonEums.TG_BUTTON.getValue(), ButtonEums.TG_BUTTON.getDescription()));
//                buttonVOS.add(new ButtonVO(ButtonEums.BH_BUTTON.getValue(), ButtonEums.BH_BUTTON.getDescription()));
//                break;
//            case 102:
//                buttonVOS.add(new ButtonVO(ButtonEums.TG_BUTTON.getValue(), ButtonEums.TG_BUTTON.getDescription()));
//                break;
//            case 103:
//                buttonVOS.add(new ButtonVO(ButtonEums.SQJJ_BUTTON.getValue(), ButtonEums.SQJJ_BUTTON.getDescription()));
//                buttonVOS.add(new ButtonVO(ButtonEums.TH_BUTTON.getValue(), ButtonEums.TH_BUTTON.getDescription()));
//                break;
//            case 104:
//                buttonVOS.add(new ButtonVO(ButtonEums.BH_BUTTON.getValue(), ButtonEums.BH_BUTTON.getDescription()));
//                buttonVOS.add(new ButtonVO(ButtonEums.BTG_BUTTON.getValue(), ButtonEums.BTG_BUTTON.getDescription()));
//                buttonVOS.add(new ButtonVO(ButtonEums.RBSY_BUTTON.getValue(), ButtonEums.RBSY_BUTTON.getDescription()));
//                break;
//            case 105:
//                buttonVOS.add(new ButtonVO(ButtonEums.TG_BUTTON.getValue(), ButtonEums.TG_BUTTON.getDescription()));
//                break;
//            case 106:
//                buttonVOS.add(new ButtonVO(ButtonEums.FJSQ_BUTTON.getValue(), ButtonEums.FJSQ_BUTTON.getDescription()));
//            case 107:
//                buttonVOS.add(new ButtonVO(ButtonEums.JS_BUTTON.getValue(), ButtonEums.JS_BUTTON.getDescription()));
//                buttonVOS.add(new ButtonVO(ButtonEums.TYJJ_BUTTON.getValue(), ButtonEums.TYJJ_BUTTON.getDescription()));
//            default:
//                System.out.println("条件不合法！");
//                break;
//        }
//
//
//        // 根据用户角色获取不同的审核按钮信息
//        return buttonVOS;
//    }

    @PostConstruct
    private void deploy() {
        // 手动部署
        Deployment deployment = repositoryService.createDeployment()
                // 从xml文件读取流程
                .addClasspathResource(xmlPath)
                // 执行部署
                .deploy();

        // 根据部署ID获取流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deployment.getId())
                .singleResult();

        // 注册监听器


        // 输出流程名
        System.out.println("Found process definition : " + processDefinition.getName());
    }

    // 转换 List<FlowableVO> 为 Page<FlowableVO>
    public Page<FlowableVO> convertListToPage(List<FlowableVO> list, long current, long size, long total) {
        // 创建一个 Page 对象
        Page<FlowableVO> page = new Page<>(current, size);

        // 计算总页数
        long totalPages = (total + size - 1) / size;

        // 如果 startIndex 超过了列表大小，说明没有数据
        long startIndex = (current - 1) * size;
        if (startIndex >= list.size()) {
            page.setTotal(total);
            page.setRecords(new ArrayList<>()); // 返回空记录
            return page;
        }

        // 计算当前页的结束索引
        long endIndex = Math.min(startIndex + size, list.size());

        // 获取当前页的数据
        List<FlowableVO> pagedList = list.subList((int) startIndex, (int) endIndex);

        // 设置分页信息
        page.setTotal(total); // 设置总数据量
        page.setRecords(pagedList); // 设置当前页数据

        return page;
    }

    // 获取候选组列表人员
    public List<String> getCandidateUsers(String taskId) {
        // 获取任务的所有身份链接
        List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(taskId);

        // 使用 Stream 流来筛选候选用户并收集到 List 中
        return identityLinks.stream()
                .filter(identityLink -> "candidate".equals(identityLink.getType()))
                .map(identityLink -> identityLink.getUserId().replace("\"", ""))
                .collect(Collectors.toList());
    }

    public String getVariables(HistoricProcessInstance instance,String variableName) {
        // 使用历史变量查询获取流程实例的变量
        // 根据流程实例ID查询变量
        List<HistoricVariableInstance> variableInstances = historyService.createHistoricVariableInstanceQuery()
                .processInstanceId(instance.getId())
                .list();
        String string = "";
        for (HistoricVariableInstance variable : variableInstances) {
            if(variableName.equals(variable.getVariableName())){
                string = String.valueOf(variable.getValue());
            }
        }
        return string;
    }
}
